package com.app.android.coliy.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.android.coliy.R;
import com.app.android.coliy.adapter.FileListAdapter;
import com.app.android.coliy.bean.LocalFileInfo;
import com.app.android.coliy.event.Event_MultiFile_Print;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.interface_.OkHttpCallBack;
import com.app.android.coliy.manager.API_LoginManager;
import com.app.android.coliy.manager.UserManager;
import com.app.android.coliy.responce.BaseResponce;
import com.app.android.coliy.responce.GetFileResponce;
import com.app.android.coliy.tool.Log;
import com.app.android.coliy.ui.activity.LoginActivity;
import com.app.android.coliy.ui.view.Comm_SubmitBtnView;
import com.app.android.coliy.ui.view.MultiStateView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2018/8/20.
 */

public class FileListFragment extends BaseFragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_filelist, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (rootView != null) {
            checkLogin();
            getData();
        }
    }

    public int type = 0;  //0 本地， 1 云目录
    List<LocalFileInfo> localFileList = new ArrayList<>();
    Handler handler = new Handler();

    Context mContext;
    View rootView;
    MultiStateView multiplestatusView;
    LinearLayout ll_login;
    RecyclerView recyclerview;
    Comm_SubmitBtnView tv_login, csb_print;
    FileListAdapter adapter;

    public boolean isMutil;

    public void setIsMutil(boolean isMutil) {
        this.isMutil = isMutil;
        adapter.setIsMutil(isMutil);
        if (isMutil) {
            csb_print.setVisibility(View.VISIBLE);
        } else {
            csb_print.setVisibility(View.GONE);
        }
    }

    private void initView() {
        multiplestatusView = rootView.findViewById(R.id.multiplestatusView);
        multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);    //页面初始化，默认为加载中状态
        multiplestatusView.setOnRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                multiplestatusView.setViewState(MultiStateView.ViewState.LOADING);
                getData();
            }
        });

        ll_login = rootView.findViewById(R.id.ll_login);
        recyclerview = rootView.findViewById(R.id.recyclerview);
        LinearLayoutManager gm = new LinearLayoutManager(mContext);
        recyclerview.setLayoutManager(gm);
        adapter = new FileListAdapter(mContext, callBack);
        recyclerview.setAdapter(adapter);

        tv_login = rootView.findViewById(R.id.tv_login);
        csb_print = rootView.findViewById(R.id.csb_print);

        tv_login.setOnClickListener(this);
        csb_print.setOnClickListener(this);

        //拖拽功能
        mItemHelper.attachToRecyclerView(recyclerview);
    }


    ItemTouchHelper mItemHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            Log.e("hsjkkk", "getMovementFlags()");
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            final int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            Log.e("hsjkkk", "onMove()");
            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();


            LocalFileInfo from = localFileList.get(fromPosition);
            LocalFileInfo to = localFileList.get(toPosition);
            int temp = from.sort;
            from.sort = to.sort;
            to.sort = temp;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    from.save();
                    to.save();
                }
            });

            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(localFileList, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(localFileList, i, i - 1);
                }
            }
            adapter.notifyItemMoved(fromPosition, toPosition);


            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//                Toast.makeText(MainActivity.this, "拖拽完成 方向" + direction, Toast.LENGTH_SHORT).show();
            Log.e("hsjkkk", "拖拽完成 方向" + direction);

        }

        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);
            Log.e("hsjkkk", "onSelectedChanged()");
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE)
                viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
        }

        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            Log.e("hsjkkk", "clearView()");
            viewHolder.itemView.setBackgroundColor(0);

        }

        //重写拖拽不可用
        @Override
        public boolean isLongPressDragEnabled() {
            Log.e("hsjkkk", "isLongPressDragEnabled()");
            return true;
        }
    });


    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            String result = (String) obj;
            if ("refresh".equals(result)) {
                getData();
            }

        }
    };


    private void checkLogin() {
        if (type == 1) {
            if (UserManager.isLogin(mContext)) {
                ll_login.setVisibility(View.GONE);
            } else {
                ll_login.setVisibility(View.VISIBLE);
            }
        } else {
            ll_login.setVisibility(View.GONE);
        }
    }

    //网路请求 获取数据
    private void getData() {
        if (type == 0) {
//            localFileList = DataSupport.findAll(LocalFileInfo.class);
            localFileList = DataSupport
//                    .select("title", "content")
//                    .where("commentcount > ?", "0")
                    .order("sort asc").find(LocalFileInfo.class);


            bindUI();
        } else {
            API_LoginManager.docs(mContext, new OkHttpCallBack() {
                @Override
                public void onSuccess(BaseResponce baseResponce) {
                    try {
                        GetFileResponce fileResponce = (GetFileResponce) baseResponce;
                        Log.i("fileResponce.data.size:" + fileResponce.data.size());
                        localFileList.clear();
                        for (int i = 0; i < fileResponce.data.size(); i++) {
                            LocalFileInfo fileInfo = new Gson().fromJson(fileResponce.data.get(i).content, LocalFileInfo.class);
                            localFileList.add(fileInfo);
                        }
                        bindUI();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(BaseResponce baseResponce) {
                    multiplestatusView.setViewState(MultiStateView.ViewState.ERROR);
                }
            });
        }
    }

    //绑定数据
    private void bindUI() {
        //排序


        adapter.setData(localFileList);
        if (adapter.getItemCount() == 0) {
            multiplestatusView.setViewState(MultiStateView.ViewState.EMPTY);
        } else {
            multiplestatusView.setViewState(MultiStateView.ViewState.CONTENT);
        }
    }

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent;
        switch (view.getId()) {
            case R.id.csb_print:
                Event_MultiFile_Print event_multiFile_print = new Event_MultiFile_Print();

                List<LocalFileInfo> localFileInfos = new ArrayList<>();
                for (LocalFileInfo localFileInfo : adapter.list) {
                    if (localFileInfo.isSelect) {
                        localFileInfos.add(localFileInfo);
                    }
                }
                event_multiFile_print.localFileInfos = localFileInfos;
                EventBus.getDefault().post(event_multiFile_print);
                ((Activity) mContext).finish();
                break;

            case R.id.tv_login:
                intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);

//                // 打开注册页面
//                RegisterPage registerPage = new RegisterPage();
//                // 使用自定义短信模板(不设置则使用默认模板)
////                registerPage.setTempCode(TEMP_CODE);
//                registerPage.setRegisterCallback(new EventHandler() {
//                    public void afterEvent(int event, int result, Object data) {
//                        // 解析注册结果
//                        if (result == SMSSDK.RESULT_COMPLETE) {
//                            @SuppressWarnings("unchecked")
//                            HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
//                            String country = (String) phoneMap.get("country");
//                            String phone = (String) phoneMap.get("phone");
//                            // 提交用户信息
////						registerUser(country, phone);
//                        }
//                    }
//                });
//                registerPage.show(mContext);

                break;

        }
    }
}
